package campfirelighter.services {
	import campfirelighter.events.RoomsEvent;
	import campfirelighter.model.Room;
	import campfirelighter.utils.UserPreferences;
	
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	
	import mx.collections.ArrayCollection;
	import mx.utils.Base64Encoder;
	
	/**
	 * @author Danny Patterson
	 */
	public class GetRoomsService extends EventDispatcher implements IService {
		
		protected var loader:URLLoader;
		
		public function GetRoomsService() {}
		
		private function onComplete(event:Event):void {
			var result:XML = XML(loader.data);
			var rooms:ArrayCollection = new ArrayCollection();
			for each(var roomData:XML in result.room) {
				var room:Room = new Room();
				room.xmlDeserialize(roomData);
				rooms.addItem(room)
			}
			dispatchEvent(new RoomsEvent(RoomsEvent.ROOMS_LOADED, rooms));
		}
		
		private function onError(event:ErrorEvent):void {
			dispatchEvent(new ErrorEvent(ErrorEvent.ERROR, false, false, event.text));
		}
		
		public function execute():void {
			var encodedCredentials:Base64Encoder = new Base64Encoder();
			encodedCredentials.insertNewLines = false;
			encodedCredentials.encode(UserPreferences.authtoken + ":" + UserPreferences.authpassword);
			var authHeader:URLRequestHeader = new URLRequestHeader("Authorization", "Basic " + encodedCredentials.flush())
			var request:URLRequest = new URLRequest();
			request.url = UserPreferences.endpoint + "/rooms.xml";
			request.requestHeaders = new Array(authHeader);
			loader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, onComplete);
			loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
			loader.load(request);
		}
		
	}
	
}